<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
require_once __DIR__.'/../../utils/checkTokenUtils.php';
require_once __DIR__.'/../../model/BorrowModel.php';
use model\BorrowModel;

// 仅允许POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error_message'] = '错误：仅支持POST请求';
    header('Location: borrow.php');
    exit;
}

// 获取并验证表单数据
$borrowId = isset($_POST['borrow_id']) ? intval($_POST['borrow_id']) : 0;
$returnTime = isset($_POST['return_time']) ? trim($_POST['return_time']) : null;
if ($returnTime === '') {
    $returnTime = null;
}
$status = isset($_POST['status']) ? intval($_POST['status']) : 0;

// 基础验证
if (!$borrowId) {
    $_SESSION['error_message'] = '错误：未获取到有效的借阅记录ID';
    header('Location: borrow.php');
    exit;
}

// 调用模型更新记录
$borrowModel = new BorrowModel();
$result = $borrowModel->updateReturnStatus($borrowId, $returnTime, $status);

if ($result !== false) {
    $_SESSION['success_message'] = '借阅记录更新成功';
} else {
    $_SESSION['error_message'] = '错误：数据库更新失败';
}

header('Location: borrow.php');
exit;